/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of JoinUs!.

JoinUs! is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

JoinUs! is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with JoinUs!. If not, see <http://www.gnu.org/licenses/>. */
package br.ufes.cwtools.joinus.util;

import java.io.*;
import java.util.*;
import javax.crypto.*;
import javax.crypto.spec.*;

public class Crypter
{
    public static String encrypt(String strkey, Map<String,String> map)
        throws Exception
    {
        SecretKey key = new SecretKeySpec(Base64.decode(strkey), "DES");
        return encrypt(key, map);
    }

    public static String encrypt(SecretKey key, Map<String,String> map)
        throws Exception
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);

        oos.writeObject(map);

        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

        cipher.init(Cipher.ENCRYPT_MODE, key);
        return Base64.encode(cipher.doFinal(bos.toByteArray()));
    }

    @SuppressWarnings("unchecked")
	public static Map<String,String> decrypt(SecretKey key, String msg)
        throws Exception
    {
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] obj = cipher.doFinal(Base64.decode(msg));

        ByteArrayInputStream bis = new ByteArrayInputStream(obj);
        ObjectInputStream ois = new ObjectInputStream(bis);

        return (Map<String,String>) ois.readObject();
    }
    
    public static byte[] serialize(Object o) throws Exception
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);

        oos.writeObject(o);

        return bos.toByteArray();
    }
}
